'use strict';

define(['controllers', 'codemirror', 'codemirror-xml', 'codemirror-javascript', '../service/backupService', , '../service/configService', 'datepicker', 'ztree'], function (controllers, CodeMirror) {
    controllers.solr.register('BackupController', ['$scope', 'BackupService', 'ConfigService', function ($scope, backupService, configService) {
        $scope.TYPE_AUTO = 1;
        $scope.TYPE_MAN = 2;

        $scope.init = function () {
            $scope.query_type = '';

            $scope.pageNo = 1;
            $scope.pageSize = 10;

            $scope.save_err = false;
        };

        $scope.initEvent = function () {
            $('#editDialog').on('shown.bs.modal', function () {
                $('#save_path').select();
            });
            $('#save_path, #save_remark').keypress(function (e) {
                if (isSubmitKeyCode(e)) {
                    $scope.save();
                }
            });
        };

        $scope.initDatepicker = function() {
            $('#query_startTime').datepicker({
                format: 'yyyy-mm-dd'
            }).on('changeDate', function (e) {
                var startTime = e.date.getDayBeginTime();
                if (startTime > $scope.query_endTime) {
                    $('#query_startTime').val(new Date($scope.query_startTime).format($scope.DATE_FORMAT));
                    return false;
                }
                $scope.query_startTime = startTime;
            });

            $('#query_endTime').datepicker({
                format: 'yyyy-mm-dd'
            }).on('changeDate', function (e) {
                var endTime = e.date.getDayEndTime();
                if (endTime < $scope.query_endTime) {
                    $('#query_endTime').val(new Date($scope.query_endTime).format($scope.DATE_FORMAT));
                    return false;
                }
                $scope.query_endTime = endTime;
            });
        };

        $scope.query = function (pageNo) {
            if (pageNo != null) {
                $scope.pageNo = pageNo;
            }
            $scope.paged = backupService.query({
                type: $scope.query_type,
                startTime: $scope.query_startTime,
                endTime: $scope.query_endTime,
                pageNo: $scope.pageNo,
                pageSize: $scope.pageSize
            });
        };

        $scope.edit = function () {
            $('#editDialog').modal('show');
        };

        $scope.validPath = function (callback) {
            if (isEmpty($scope.save_path)) {
                $scope.save_err = true;
                $scope.save_errMsg = '路径不能为空';
            }
            backupService.exist({
                path: $scope.save_path
            }, function (data) {
                if (data.flag) {
                    if (callback != null) {
                        callback();
                    }
                } else {
                    $scope.save_err = true;
                    $scope.save_errMsg = '备份路径不存在，请重新输入';
                    $('#save_path').select();
                }
            });
        };

        $scope.save = function () {
            $scope.save_err = false;
            $scope.validPath(function() {
                backupService.save({}, {
                    path: $scope.save_path,
                    remark: $scope.save_remark
                }, function () {
                    $('#editDialog').modal('hide');
                    $scope.save_path = '';
                    $scope.save_remark = '';
                    $scope.query();
                });
            });
        };

        $scope.confirmRemove = function (backup) {
            $scope.removeId = backup.id;
            $('#removeDialog').modal('show');
        };

        $scope.remove = function () {
            backupService.remove({id: $scope.removeId}, function () {
                $scope.removeId = null;
                $('#removeDialog').modal('hide');
                $scope.query();
            });
        };

        var setTreeNodes = function (zkNodes, treeNodes) {
            if (zkNodes != null && zkNodes.length > 0) {
                for (var i = 0; i < zkNodes.length; i++) {
                    var zkNode = zkNodes[i];
                    var treeNode = {
                        id: zkNode.id,
                        pId: zkNode.parentId,
                        name: zkNode.relativePath
                    };
                    if (zkNode.parentId == 0) {
                        treeNode.open = true;
                    }
                    treeNodes.push(treeNode);
                    setTreeNodes(zkNode.children, treeNodes);
                }
            }
        };

        $scope.view = function (backup) {
            backupService.getNodes({id: backup.id}, function (zkNodes) {
                for (var i = 0; i < zkNodes.length; i++) {
                    zkNodes[i].parentId = 0;
                }

                $scope.treeNodes = [];
                setTreeNodes(zkNodes, $scope.treeNodes);

                $scope.loadZkTree();
                $scope.loadCodeEditor();

                $scope.zkTree.selectNode($scope.zkTree.getNodes()[0], false);
                $scope.viewNode($scope.zkTree.getNodes()[0].id);

                $('#viewDialog').modal('show');
            });
        };

        $scope.loadCodeEditor = function () {
            if ($scope.content_editor == null) {
                $scope.content_editor = CodeMirror.fromTextArea(document.getElementById("backup_code"), {
                    mode: "application/xml",
                    styleActiveLine: true,
                    lineNumbers: true,
                    lineWrapping: true,
                    readOnly: true
                });
            }
        };

        $scope.viewNode = function (treeId) {
            configService.get({id: treeId}, function (node) {
                if (/\.xml$/.test(node.path)) {
                    $scope.content_editor.setOption('mode', 'application/xml');
                } else {
                    $scope.content_editor.setOption('mode', 'application/json');
                }
                $scope.content_editor.setValue(node.data == null ? '' : node.data);
            });
        };

        $scope.loadZkTree = function () {
            if ($scope.zkTree != null) {
                $scope.zkTree.destroy();
            }
            var setting = {
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    onClick: function (e, treeId, treeNode) {
                        $scope.viewNode(treeNode.id);
                    }
                }
            };
            $scope.zkTree = $.fn.zTree.init($("#zkTree"), setting, $scope.treeNodes);
        };

        $scope.init();
        $scope.initDatepicker();
        $scope.initEvent();
        $scope.query();
    }]);
});